#include "Maze.h"
#include "Treasure.h"
#include "Macro.h"

namespace Implement
{
	using namespace Core::GameLogic;
	using namespace Graphics;
	using namespace  Core::Devices;

	Maze::Maze(Drawable* image, int mapWidth, int mapHeight, int blockWidth,int blockHeight):
		SimpleMap(mapWidth,mapHeight,blockWidth,blockHeight),
		SpriteTile(blockWidth,blockHeight,image,BASE_SIZE),
		m_Pos(0,0),	m_Money(0)

	{
		this->Init();
	}

	Maze::Maze(Drawable* image, const std::string& filename, int blockWidth,int blockHeight):
		SimpleMap(filename,blockWidth,blockHeight),
		SpriteTile(blockWidth,blockHeight,image,BASE_SIZE),
		m_Pos(0,0),	m_Money(0)

	{
		this->Init();
	}

	Maze::~Maze(void)
	{
		PTR_DELETE(m_Data.pData);
		PTR_DELETE(m_Data.pStep);
	}

	void Maze::Init(void)
	{
		Core::Size size = this->GetMapSizeByTile();
		m_Data.width = size.width;
		m_Data.count = size.width * size.height;
		m_Data.pData = new DWORD[m_Data.count];
		m_Data.pStep = 0;

		int i = 0;
		Position p(0,0);		
		for(p.y = 0;p.y<size.height;p.y++)
		{
			for(p.x = 0;p.x<size.width;p.x++)
			{
				m_Data.pData[i] = SimpleMap::GetLogicMap().GetInfo(p).info;
				i++;
			}
		}
	}
	const Position& Maze::GetPos()
	{
		return m_Pos;
	}
	// Get the tile data for rendering
	const Graphics::SpriteTile::TileData& Maze::GetData(void)
	{
		return m_Data;
	}
	void Maze::OnMove(SourceType& source)
	{
		SimpleMap::OnMove(source);

		const SimpleMap::MapInfo& info=this->SimpleMap::GetInfo( source.GetPosition() );
		if(info.elements.size()>1)
		{
			for(std::set<Element*>::const_iterator i=info.elements.begin();i!=info.elements.end();i++)
			{
				
				if(*i==&source) continue;
				if(&typeid(**i)==&typeid(source)) continue;
				Treasure* const t=dynamic_cast<Treasure* const> (*i);
				m_Money += t->GetMoney();
				Element* tempi = (*i);
				this->RemoveElement((*i));

				Position start(0,0);
				SimpleMap::MapInfo mi;
				Core::Size ms = this->GetMapSizeByTile();
				do
				{
					start.Set(rand()%ms.width,rand()%ms.height);
					mi = this->SimpleMap::GetInfo(this->TileToGrid(start) );
				}while(mi.info == SimpleMap::MapInfo::BLOCK || mi.elements.size()!=0 );
				tempi->SetPosition(this->TileToGrid(start) );
				this->AddElement(tempi);
				break;
			}
		}
	}
	int Maze::GetMoney(void)
	{
		return m_Money;
	}

}
